package com.ailk.cuc.autotestbg.common.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.logging.Log;

import com.ailk.cuc.autotestbg.common.constants.StaticParam;

public class DbUtils {

	private static Log logger = LogUtils.getLogger(DbUtils.class.getName());
	private static Connection conn = null;
	public static Connection getConnection(){
		return getConnection(null);
	}
	
	public static Connection getConnection(String ecsDBInstatce){
		logger.debug("开始获取数据库连接");
		try {
			if(conn == null || conn.isClosed()){
				Class.forName("oracle.jdbc.driver.OracleDriver");
				if(null == ecsDBInstatce){
					conn = DriverManager.getConnection(StaticParam.url, StaticParam.user, StaticParam.password);
				}else{
					String[] ecsDBInfo = StaticParam.ecsDBInfoMap.get(ecsDBInstatce);
					conn = DriverManager.getConnection(ecsDBInfo[0], ecsDBInfo[1], ecsDBInfo[2]);
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			logger.error("oracle.jdbc.driver.OracleDriver can't find");
			logger.error(e.getMessage());
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error("获取数据库连接发生异常");
			logger.error(e.getMessage());
		}
		logger.debug("获取数据库连接完毕");
		return conn;
	}
	
	public static void close(ResultSet rs, Statement stmt, Connection conn){
		if (rs != null) {
			try {
				rs.close();
				logger.debug("ResultSet关闭");
			} catch (SQLException e) {
				e.printStackTrace();
				logger.error("关闭ResultSet异常");
				logger.error(e.getMessage());
				throw new RuntimeException();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
				logger.debug("Statement关闭");
			} catch (SQLException e) {
				e.printStackTrace();
				logger.error("关闭Statement异常");
				logger.error(e.getMessage());
				throw new RuntimeException();
			}
		}
		if (conn != null) {
			try {
				conn.close();
				logger.debug("Connection关闭");
			} catch (SQLException e) {
				e.printStackTrace();
				logger.error("关闭Connection异常");
				logger.error(e.getMessage());
				throw new RuntimeException();
			}
		}
	}
}
